import {toast} from "./common";
import config from '../config.js'

export default {
	install(Vue) {
		Vue.mixin({
			data() {
				return {
					arrNew: [],
					classNameNew:'',
				}
			},
			methods: {
				todayStr: function (date = new Date()){
					const y = date.getFullYear() //1
					const m = (date.getMonth() + 1 + '').padStart(2, '0') //不足两位补0
					const d = (date.getDate() + '').padStart(2, '0')
					return y + '-' + m + '-' + d
				},
				showClassName: function () {
					this.$refs.popup.open('right');

					this.arrNew = this.dataList.filter(item => {
						if (item.className.indexOf(this.classNameNew) != -1) {
							return item;
						}
					})
				},
				bindPickerChange: function(item) {
					// alert(item.classId)
					this.getClassStuListByClassId(item.classId)
					this.classNameNew = item.className;
					this.$refs.popup.close();
					this.$forceUpdate()
				},
				notEmpty(val){
					return !this.isEmpty(val);
				},
				/**
				 * str或array为null或长度为0返回true 其它返回false
				 * 注意val.keys===0也返回false
				 * @param val
				 * @return {boolean}
				 */
				isEmpty(val){
					if(!val){
						return true;
					}
					if(typeof val === "string" || Array.isArray(val)){
						return val.length === 0;
					}
					return false;
				},
				toast: function (title, duration = 1500, icon='none'){
					toast(title,duration,icon);
				},
				execute: function (action,timeout=0){
					if(timeout > 0){
						setTimeout(action,timeout);
					}else {
						action();
					}
				},
				goBack: function(timeout=0, pageNum=1){
					if(timeout > 0){
						setTimeout(function (){
							uni.navigateBack({
								delta: pageNum
							});
						},timeout);
					}else {
						uni.navigateBack({
							delta: pageNum
						});
					}
				},
				goPage: function (url,timeout=0){
					this.execute(()=>{
						uni.navigateTo({
							url: url
						});
					},timeout);
				},
				goPageNoHistory: function (rul,timeout=0){
					this.execute(()=>{
						uni.redirectTo({
							url: url
						});
					},timeout);
				},
				goPageClearHistory: function (rul,timeout=0){
					this.execute(()=>{
						uni.reLaunch({
							url: url
						});
					},timeout);
				},
				reload(){
					// 获取当前页面的路径
					let currentPage = getCurrentPages().pop();
					// 如果当前页面有参数，需要将其转换成查询字符串
					let query = currentPage.options ? '?' + Object.keys(currentPage.options).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(currentPage.options[key])}`).join('&') : '';
					// 重定向到当前页面，实现重新加载
					uni.redirectTo({
						url: `/${currentPage.route}${query}`
					});
				},
				handleRes: function (res,successHint=null,failHint=null){
					return new Promise((resolve,reject) => {
						let success = res.hasOwnProperty('code') && res.code === 200;
						success = success || (res.hasOwnProperty('status') && res.status === 200);
						if(success){
							if(successHint){
								if(typeof successHint === "boolean"){
									toast("操作成功");
								}else{
									toast(successHint);
								}
							}
							resolve(res.data);
						}else {
							if(failHint){
								if(typeof failHint === 'boolean'){
									let msg = res.message || '操作失败';
									toast(msg)
								}else {
									toast(failHint);
								}
							}
							reject(res.message);
						}
					});
				},
				handleImageUrl(url){
					if(!url || url.length < 1 || /^(https?:|mailto:|tel:|blob:|wxfile:)/.test(url)){
						return url;
					}
					if(url.startsWith('/') && url.length > 1){
						url = url.substring(1);
					}
					return config.baseUrl + "app/common/downloadFileImg?filename=" + url;
				},
				getStorage(key,defaultValue=null){
					let value = uni.getStorageSync(key);
					return value === undefined || value === null ? defaultValue : value;
				},
				getErrorResMsg(error,defaultErrorMessage='操作失败'){
					return !error || !error.data || !error.data.message ? defaultErrorMessage : error.data.message;
				},
				showLoadingByQuery(duration = null){
					return this.showLoading('加载中...',duration);
				},
				showLoadingBySubmit(duration = null){
					return this.showLoading('提交中...',duration);
				},
				showLoading(title=null,duration=null,mask=true){
					let options = {
						mask: mask // 显示透明蒙层，防止触摸穿透
					};
					if(title){
						options['title'] = title;
					}
					uni.showLoading(options);

					if(duration){
						this.hideLoading(duration);
					}
				},
				hideLoading(duration=null){
					if(!duration){
						uni.hideLoading();
					}
					setTimeout(()=>uni.hideLoading(),duration);
				},
			}
		})
	}
}
